package com.rest.server;

import java.util.Locale;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.rest.model.CalculatorOpration;
import com.rest.model.CalculatorResponse;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {

	private static final Logger logger = LoggerFactory
			.getLogger(HomeController.class);
	private String _token = null;

	@Autowired
	@RequestMapping(value = "/user/{name}", method = RequestMethod.GET)
	public @ResponseBody String login(Locale locale, 
						Model model,
						@PathVariable("name") String name, 
						HttpServletRequest request,
						HttpServletResponse response) {
		
		logger.info("Welcome {}! The client locale is {}.", name, locale);

		_token = UUID.randomUUID().toString();
		return _token;
	}
	
	@Autowired
	@RequestMapping(value = "/calculator", method = RequestMethod.POST)
	public @ResponseBody CalculatorResponse calcullate(Locale locale, 
						Model model,
						@RequestBody CalculatorOpration opration, 
						HttpServletRequest request,
						HttpServletResponse response) {
		
		String token = request.getHeader("token");
		
		if(!token.equals(_token)){
			CalculatorResponse result = new CalculatorResponse();
			result.setError("Invalid token");
			return result;
		}
		
		double resultValue;
		String action = opration.getOpration();
		
		if (action.equals("+")) {
			resultValue = opration.getFirst() + opration.getSecond();
		} else if (action.equals("-")) {
			resultValue = opration.getFirst() - opration.getSecond();
		} else if (action.equals("*")) {
			resultValue = opration.getFirst() * opration.getSecond();
		} else if (action.equals("/")) {
			resultValue = opration.getFirst() / opration.getSecond();
		} else {
			CalculatorResponse result = new CalculatorResponse();
			result.setError("Invalid opration");
			return result;
		}

		CalculatorResponse result = new CalculatorResponse();
		result.setValue(resultValue);
		return result;
	}
}
